package com.java.mvc;

import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

public class HandlerMapping {
    private static final Map<String, MVCMapping> data = new HashMap<>();

    public static MVCMapping get(String uri) {
        return data.get(uri);
    }

    public static void init(InputStream is) {
        Properties pps = new Properties();
        try {
            pps.load(is);
            final Collection<Object> values = pps.values();
            for (Object value : values) {
                final Class<?> cla = Class.forName((String) value);
                final Object o = cla.getConstructor().newInstance();
                final Method[] methods = cla.getMethods();
                for (Method method : methods) {
                    final Annotation[] annotations = method.getAnnotations();
                    for (Annotation annotation : annotations) {
                        if (annotation instanceof Body) {
                            final MVCMapping mvcMapping = new MVCMapping(method, o, ResponseType.Text);
                            data.put(((Body) annotation).value(), mvcMapping);
                        } else if (annotation instanceof View) {
                            final MVCMapping mvcMapping = new MVCMapping(method, o, ResponseType.View);
                            data.put(((View) annotation).value(), mvcMapping);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class MVCMapping {
        private final Method method;
        private final Object object;
        private final ResponseType type;

        public MVCMapping(Method method, Object object, ResponseType type) {
            this.method = method;
            this.object = object;
            this.type = type;
        }

        public Method getMethod() {
            return method;
        }

        public Object getObject() {
            return object;
        }

        public ResponseType getType() {
            return type;
        }
    }
}
